package eclipse.weibo.modle.control;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.VisibilityWindowListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class BrowserDialog {
	private static Shell shell = getShell();
	private static Browser browser = getBrowser();

	private BrowserDialog() {
	}

	private static Shell getShell() {
		Shell newShell = new Shell();
		newShell.setLayout(new FillLayout());
		return newShell;
	}

	private static Browser getBrowser() {
		browser = new Browser(shell, SWT.NONE);
		initialize(shell.getDisplay(), browser);
		return browser;
	}

	public static void open(String url) {
		shell.open();
		browser.setUrl(url);
	}

	static void initialize(final Display display, Browser browser) {
		browser.addVisibilityWindowListener(new VisibilityWindowListener() {
			public void hide(WindowEvent event) {
				Browser browser = (Browser) event.widget;
				Shell shell = browser.getShell();
				shell.setVisible(false);
			}

			public void show(WindowEvent event) {
				Browser browser = (Browser) event.widget;
				Shell shell = browser.getShell();
				if (event.location != null) {
					shell.setLocation(event.location);
				}
				if (event.size != null) {
					Point size = event.size;
					shell.setSize(shell.computeSize(size.x, size.y));
				}
				shell.open();
			}
		});
	}
}
